<?php
/**
 * IMPORTANT: Do not use this controller for writing your own code!!
 * @return
 */
class Import extends Controller {

    function Import() {
        parent::Controller();
        $this->load->model('model_data');
        $this->load->model('model_import');
        if (!$this->usersession->userLoggedIn()) {
            $aResponse = array("error" => true, "description" => "Sesiunea a expirat", "type" => "nosession");
            die(json_encode($aResponse));
        }
    }


    function import_file($data, $rows, $customs) {

        //$send_present = '1';
        $esteCeva = false;
        $problema = 0;

        $let_1 = array("&Icirc;", "&icirc;");
        $let_2 = array("I", "i");


        if (is_array($data)) {
            foreach ($data as $key => $element)
            {
                //$data[$key]=html_entity_decode(str_replace($let_1,$let_2,htmlentities($element)));
                if (trim($element) != '') $esteCeva = true;
            }
        }
        if (!$esteCeva) return;


        $dataPerson["company"] = strUpper($data["1"]);
        $dataPerson["lname"] = strTitle($data["2"]);
        $dataPerson["fname"] = strTitle($data["3"]);
        $dataPerson["sex"] = $data["4"];
        $dataPerson["domain_id"] = strTitle($data["5"]);
        $dataPerson["domain_sub_id"] = strTitle($data["6"]);
        $dataPerson["position_id"] = strTitle($data["7"]);
        $dataPerson["position_sub_id"] = strTitle($data["8"]);
        $dataPerson["division_id"] = strTitle($data["9"]);
        $dataPerson["address"] = strTitle($data["10"]);
        $dataPerson["address2"] = strTitle($data["11"]);
        $dataPerson["city_id"] = strTitle($data["12"]);
        $dataPerson["county_id"] = strTitle($data["13"]);
        $dataPerson["phone"] = strTitle($data["14"]);
        $dataPerson["mobil"] = strTitle($data["15"]);
        $dataPerson["email"] = strLower($data["16"]);
        $dataPerson["email2"] = strLower($data["17"]);
        $dataPerson["web"] = strLower($data["18"]);
        $dataPerson["birth"] = strTitle($data["19"]);
        $dataPerson["age"] = strTitle($data["21"]);
        $dataPerson["income"] = $data["22"];
        $dataPerson["available"] = $data["23"];
        $dataPerson["priority"] = $data["24"];
        $dataPerson["turnover"] = $data["25"];
        $dataPerson["employees"] = $data["26"];
        $dataPerson["obs"] = strTitle($data["27"]);
        $dataPerson["obs_company"] = strTitle($data["28"]);
        $dataPerson["cui"] = strTitle($data["29"]);
	    $dataPerson["turnover2010"] = $data["30"];
	    $dataPerson["turnover2011"] = $data["31"];

        $dataPerson["create_by"] = $customs['created_by'];
        $dataPerson["client_id"] = $customs['client_id'];
        $dataPerson["type"] = $customs['type'];

        if ($dataPerson["birth"] == "") {
            $dataPerson["birth"] = null;
        }

        $key = array_search($dataPerson["sex"], $customs["sex"]);
        if ($key !== FALSE) $dataPerson["sex"] = $key;
        $key = array_search($dataPerson["age"], $customs["age"]);
        if ($key !== FALSE) $dataPerson["age"] = $key;
        $key = array_search($dataPerson["income"], $customs["income"]);
        if ($key !== FALSE) $dataPerson["income"] = $key;
        $key = array_search($dataPerson["turnover"], $customs["turnover"]);
        if ($key !== FALSE) $dataPerson["turnover"] = $key;
	     $key = array_search($dataPerson["turnover2010"], $customs["turnover"]);
        if ($key !== FALSE) $dataPerson["turnover2010"] = $key;
	    $key = array_search($dataPerson["turnover2011"], $customs["turnover"]);
        if ($key !== FALSE) $dataPerson["turnover2011"] = $key;
        $key = array_search($dataPerson["available"], $customs["available"]);
        if ($key !== FALSE) {
            $dataPerson["available"] = $key;
        }


        $key = array_search($dataPerson["priority"], $customs["priority"]);
        if ($key !== FALSE) $dataPerson["priority"] = $key;
        //$key = array_search($dataPerson["send_present"], $customs["send_present"]);          if($key!==FALSE) $dataPerson["send_present"]=$key;       else $dataPerson["send_present"]=0;

        $key = array_search($dataPerson["employees"], $customs["employees"]);
        if ($key !== FALSE) $dataPerson["employees"] = $key;


        if ($dataPerson["city_id"] != "")
            foreach ($customs["city"] as $city)
                if (strLower($city["name"]) == strLower($dataPerson["city_id"]))
                    $dataPerson["city_id"] = $city["id"];


        if ($dataPerson["county_id"] != "")
            foreach ($customs["county"] as $county)
                if (strLower($county["name"]) == strLower($dataPerson["county_id"]))
                    $dataPerson["county_id"] = $county["id"];


        if ($dataPerson["division_id"] != "")
            foreach ($customs["division"] as $division)
                if (strLower($division["name"]) == strLower($dataPerson["division_id"]))
                    $dataPerson["division_id"] = $division["id"];

        /*foreach($customs["client"] as $client)
      if(trim(mb_convert_case($client["name"], MB_CASE_LOWER, "UTF-8"))==trim(mb_convert_case($dataPerson["client_id"], MB_CASE_LOWER, "UTF-8")) )
      $dataPerson["client_id"]=$client["id"];*/

        if ($dataPerson["domain_id"] != "")
            foreach ($customs["domain"] as $domain)
                if (strLower($domain["name"]) == strLower($dataPerson["domain_id"])) {
                    $dataPerson["domain_id"] = $domain["id"];
                }

        if ((is_numeric($dataPerson["domain_id"])) && ($dataPerson["domain_sub_id"] != ""))
            foreach ($customs["domain_sub"] as $domain_sub)
                if ((strLower($domain_sub["name"]) == strLower($dataPerson["domain_sub_id"])) && ((int) $domain_sub["parent_id"] == (int) $dataPerson["domain_id"]))
                    $dataPerson["domain_sub_id"] = $domain_sub["id"];

        if ($dataPerson["position_id"] != "")
            foreach ($customs["position"] as $position)
                if (strLower($position["name"]) == strLower($dataPerson["position_id"]))
                    $dataPerson["position_id"] = $position["id"];

        if ((is_numeric($dataPerson["position_id"])) && ($dataPerson["position_sub_id"] != ""))
            foreach ($customs["position_sub"] as $position_sub)
                if ((strLower($position_sub["name"]) == strLower($dataPerson["position_sub_id"])) && ((int) $position_sub["parent_id"] == (int) $dataPerson["position_id"]))
                    $dataPerson["position_sub_id"] = $position_sub["id"];

        $dataPerson["duplicat"] = 0;

        //caut sa vad daca e dublura
        $this->db->flush_cache();
        $this->db->select("person_id");
        $this->db->where("lower(lname)", strLower($dataPerson["lname"]));
        $this->db->where("lower(fname)", strLower($dataPerson["fname"]));
        $this->db->where("lower(address)", strLower($dataPerson["address"]));
        $query = $this->db->get("persons");
        $dataPerson["duplicat"] = 0;
        if ($query->num_rows() >= 1) {
            $result = $query->row();
            $dataPerson["duplicat"] = $result->person_id;
        }


        $this->db->flush_cache();
        $this->model_import->insert_import($dataPerson);

        // Some code happens here


        return true;
    }


    function importData() {


        header('Content-type: text/html; charset=utf-8');

        $this->load->library('Spreadsheet_Excel_Reader', "reader");

        $field_name = "file";

        $config['upload_path'] = $this->config->item('upload_prov');
        $config['allowed_types'] = '*';
        $config['remove_spaces'] = TRUE;
        $config['overwrite'] = FALSE;
        $this->upload->initialize($config);

        if (!$this->upload->do_upload($field_name)) {
            $aResponse = array("error" => TRUE, "description" => "Probleme la upload", "success" => FALSE);
            echo json_encode($aResponse);
        }
        else
        {


            $data = $this->upload->data();
            $sFileName = $data['file_name'];
            $data = new Spreadsheet_Excel_Reader();
            $data->setUTFEncoder('iconv');
            $data->setOutputEncoding('UTF-8');

            //$data->setOutputEncoding('CP1251');

            $data->read($config['upload_path'] . $sFileName);
            $rows = count($data->sheets[0]['cells']);


            $customs = array();
            $customObject = array();

            $customs["age"] = $this->config->item("ageContact");
            $customs["income"] = $this->config->item("incomeContact");

            $customs["employees"] = $this->config->item("employeeContact");
            $customs["available"] = $this->config->item("availableContact");
            $customs["priority"] = $this->config->item("priorityContact");
            $customs["sex"] = $this->config->item("sexContact");
            $customs["turnover"] = $this->config->item("turnoverContact");

            $customObject['table'] = "city";
            $customs['city'] = $this->model_data->bringAllObject($customObject);
            $customObject['table'] = "county";
            $customs['county'] = $this->model_data->bringAllObject($customObject);
            $customObject['table'] = "division";
            $customs['division'] = $this->model_data->bringAllObject($customObject);

            $customs['created_by'] = $_POST["user"];
            $customs['client_id'] = $_POST["client_id"];
            $customs['type'] = $_POST["type"];

            if ($customs['created_by'] == "") {
                $aResponse = array("error" => TRUE, "description" => "Probleme la upload", "success" => FALSE);
                echo json_encode($aResponse);
                return;
            }

            $customObject['table'] = "domain";
            $customObject['level'] = "0";
            $customs['domain'] = $this->model_data->bringAllObject($customObject);


            $customObject['table'] = "domain";
            $customObject['level'] = "1";
            $customs['domain_sub'] = $this->model_data->bringAllObject($customObject);

            $customObject['table'] = "position";
            $customObject['level'] = "0";
            $customs['position'] = $this->model_data->bringAllObject($customObject);

            $customObject['table'] = "position";
            $customObject['level'] = "1";
            $customs['position_sub'] = $this->model_data->bringAllObject($customObject);

            //sterg date de import ale userului in cauza
            $this->model_import->delete_import($customs['created_by']);


            //print_r (count($data->sheets[0]["cells"]));

            if ($rows == '') $rows = 0;
            for ($j = 1; $j <= $rows; $j++) {
                if ($j > 1) {
                    $result = $this->import_file($data->sheets[0]['cells'][$j], $rows, $customs);
                }
            }


            $aResponse = array("error" => false, "description" => "Datele au fost salvate", "success" => true);
            echo json_encode($aResponse);
        }
    }


    function bringImport() {
        $table = 'persons_temp';

        $s_limit = $this->input->post("start");
        $e_limit = $this->input->post("limit");
        $dir = $this->input->post("dir");
        $sort = $this->input->post("sort");

        switch ($sort)
        {
            case 'lname':
                $sort = "$table.lname";
                break;
            case 'fname':
                $sort = "$table.fname";
                break;
            case 'modify_by':
                $sort = "$table.modify_by";
                break;
            case 'address':
                $sort = "$table.address";
                break;
            case 'date_modified':
                $sort = "$table.date_modified";
                break;
        }
        echo json_encode($this->model_import->bringImport($table, $s_limit, $e_limit, $sort, $dir, $_POST));
    }

    function modifyContact() {
        $result = $this->model_import->modifyContact($_POST);
        $aResponse = array("error" => false, "description" => "Datele au fost salvate", "success" => true);
        echo json_encode($aResponse);
    }

    function transferContact() {

        if ($this->input->post("transfer") != "transfer_extern") {
            $result = $this->model_import->transferContact($_POST);
            $result["contacts"] = json_encode($result["contacts"]);
            $this->load->model("model_campaign");
            $this->model_campaign->opContact($result);
        }

        if ($this->input->post("transfer") == "transfer_extern") {
            $this->model_import->transferExternContact($_POST);
        }

        $aResponse = array("error" => false, "description" => "Datele au fost salvate", "type" => "data");
        echo json_encode($aResponse);
    }

    function verifyContact() {
        $result = $this->model_import->verifyContact($_POST);
        $aResponse = array("error" => false, "description" => "Datele au fost verificate");
        echo json_encode($aResponse);
    }

    function deleteContact() {
        $result = $this->model_import->deleteContact($_POST);
        $aResponse = array("error" => false, "description" => "Datele au fost salvate", "success" => true);
        echo json_encode($aResponse);
    }


}

